package cn.hpclub.server.cfg;

import cn.hpclub.server.interceptor.HtmlHandler;
import cn.hpclub.server.util.PropertiesUtils;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.jfinal.BeetlRenderFactory;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.ext.plugin.quartz.QuartzPlugin;
import com.jfinal.ext.plugin.tablebind.AutoTableBindPlugin;
import com.jfinal.ext.plugin.tablebind.SimpleNameStyles;
import com.jfinal.ext.route.AutoBindRoutes;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.dialect.MysqlDialect;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.redis.*;

import cn.dreampie.shiro.core.ShiroPlugin;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.ext.xss.XssHandler;
import cn.hpclub.server.model.Organization;
import cn.hpclub.server.plugin.SsdbPlugin;
import cn.hpclub.server.restful.RestKit;
import cn.hpclub.server.security.MyJdbcAuthzService;
import cn.hpclub.server.security.MyShiroInterceptor;
import cn.hpclub.server.security.ShiroExt;
import cn.hpclub.server.util.InterfaceUtil;

public class JFWebConfig extends JFinalConfig {

    /**
     * 供Shiro插件使用。
     */
    Routes routes;

    @Override
    public void configConstant(Constants me) {
        // SqlReporter.setLogger(true);
        me.setErrorView(401, "/401.html");
        me.setErrorView(403, "/403.html");
        me.setError404View("/404.html");
        me.setError500View("/500.html");

        // 设定Beetl
        me.setMainRenderFactory(new BeetlRenderFactory());
        // 设定为开发者模式
        me.setDevMode(false);
        me.setMaxPostSize(1024 * 1024 * 30);
        // Beetl
        GroupTemplate gt = BeetlRenderFactory.groupTemplate;
        gt.registerFunctionPackage("so", new ShiroExt());

        // ActivitiesController.hostPrefix =
        // PropKit.use("serverConfig.properties").get("hostPrefix");
    }

    @Override
    public void configRoute(Routes me) {
        this.routes = me;
        // 配置路由，三个参数：访问路径（API版本），jfinal路由对象，要扫描的包(包下加了API注解的controller会被扫描)
        RestKit.buildRoutes("/api/v1", me, "cn.hpclub.server.controller.client");
        me.add(new AutoBindRoutes());
    }

    @Override
    public void configPlugin(Plugins me) {

        // 加载数据库配置文件
//        loadPropertyFile("jdbc.properties");
//        // mysql
//        String url = getProperty("jdbcUrl");
//        String username = getProperty("user");
//        String password = getProperty("password");
//        String driverClass = getProperty("driverClass");
//        String filters = getProperty("filters");
//        int initialSize = getPropertyToInt("db.initialSize");
//        int minIdle = getPropertyToInt("db.minIdle");
//        int maxActive = getPropertyToInt("db.maxActive");
//        long maxWait = getPropertyToInt("db.maxWait");

        PropertiesUtils.Prop prop = PropertiesUtils.use("jdbc.properties");
        String url = prop.get("jdbcUrl");
        String username = prop.get("user");
        String password = prop.get("password");
        String driverClass = prop.get("driverClass");
        String filters = prop.get("filters");
        int initialSize = prop.getInt("db.initialSize");
        int minIdle = prop.getInt("db.minIdle");
        int maxActive = prop.getInt("db.maxActive");
        long maxWait = prop.getInt("db.maxWait");

        // mysql 数据源
        DruidPlugin dsMysql = new DruidPlugin(url, username, password, driverClass, filters);
        dsMysql.set(initialSize, minIdle, maxActive);
        dsMysql.setMaxWait(maxWait);

        me.add(dsMysql);

        ActiveRecordPlugin arpMysql = new ActiveRecordPlugin("mysql", dsMysql);
        arpMysql.setShowSql(false);

        me.add(arpMysql);

        AutoTableBindPlugin atbp = new AutoTableBindPlugin(dsMysql, SimpleNameStyles.LOWER);
        atbp.setShowSql(false);
        atbp.setDialect(new MysqlDialect());// 配置MySql方言
        me.add(atbp);

        // 加载Shiro插件
        me.add(new ShiroPlugin(routes, new MyJdbcAuthzService()));

        // 加载缓存配置文件
        loadPropertyFile("ssdb.properties");

        boolean enabled = getPropertyToBoolean("ssdb.enabled");
        String cache = getProperty("ssdb.cache");
        String host = getProperty("ssdb.host");
        int port = getPropertyToInt("ssdb.port");
        String pwd = getProperty("ssdb.password");

        if (enabled) {
            SsdbPlugin ssdb;
            if (StrKit.notBlank(pwd)) {
                ssdb = new SsdbPlugin(cache, host, port, pwd);
            } else {
                ssdb = new SsdbPlugin(cache, host, port);
            }
            ssdb.setEnabled(true);
            me.add(ssdb);
        } else {
            SsdbPlugin ssdb = new SsdbPlugin();
            ssdb.setEnabled(false);
        }

        QuartzPlugin quartzPlugin = new QuartzPlugin("job.properties");
        me.add(quartzPlugin);

        configRedisPlugin(me);

    }

    public void configRedisPlugin(Plugins plugins){

        loadPropertyFile("redis.properties");

        String use = getProperty("redis.use");
        if("true".equalsIgnoreCase(use)){
            String cacheName = getProperty("redis.cache");
            String host = getProperty("redis.host");
            int port = getPropertyToInt("redis.port");
            String pwd = getProperty("redis.password");
            int timeout = getPropertyToInt("redis.timeout");//链接超时时间

            //缓存user模块 到 redis
            RedisPlugin userRedis = new RedisPlugin(cacheName, host, port, timeout, pwd);
            plugins.add(userRedis);
        }


    }

    @Override
    public void configInterceptor(Interceptors me) {
        me.add(new MyShiroInterceptor());
    }

    @Override
    public void configHandler(Handlers me) {
        me.add(new HtmlHandler());
        // 配置XSS handler
        me.add(new XssHandler("/api/v1"));
        // 配置handler
        RestKit.buildHandler(me);

    }

    public void afterJFinalStart() {
        try {
            int id = Db.findFirst("select " + Organization.ID + " from " + Constant.Table.ORGANIZATION + " where "
                    + Organization.ORGTYPE + "=1").getInt(Organization.ID);
            InterfaceUtil.ID_TOP = id;
            // Ssdb.use().set(Constant.Cache.ID_TOP, id);

            id = Db.findFirst("select " + Organization.ID + " from " + Constant.Table.ORGANIZATION + " where "
                    + Organization.NUMCODE + "=2").getInt(Organization.ID);
            InterfaceUtil.ID_CHENGDU = id;

            // Ssdb.use().set(Constant.Cache.ID_CHENGDU, id);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
